package com.explorati.LeetCode120.minimumTotal;

import java.util.List;

/**
 * 120. Triangle
 * 
 * Given a triangle, find the minimum path sum from top to bottom. Each step you
 * may move to adjacent numbers on the row below.
 * 
 * For example, given the following triangle [ [2], [3,4], [6,5,7], [4,1,8,3] ]
 * The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).
 * 
 * @author explorati
 *
 */
public class Solution {
	public int minimumTotal(List<List<Integer>> triangle) {

		// 三角形如果小于二，如果唯一，直接跳出循环
		// 三角形如果大于等于2的话，从倒数第二排开始，第一个数等于下一排第一个和第二个数的最小值+此数，以此类推
		for (int i = triangle.size() - 2; i >= 0; i--) {
			for (int j = 0; j <= i; j++) {
				triangle.get(i).set(j,
						triangle.get(i).get(j) + Math.min(triangle.get(i + 1).get(j), triangle.get(i + 1).get(j + 1)));
			}
		}
		return triangle.get(0).get(0);
	}
}
